#include <stdint.h>
#include <string.h>
#include <stdio.h>
#include "profiler.h"

#if PROFILER
struct prof_func {
	char name[32];
	int cnt;
	int64_t last_start;
	int64_t time_spent;
};

struct prof_func funcs[16];
int funcs_cnt = 0;

#ifdef __i386__
inline int64_t now() {
	return 0L;
}
#else
#include <io.h>
#include <signal.h>
inline int64_t now() {
	return (localtime << 16 | TAR);
}
#endif

void prof_init() {
	/* Nop */
}

void prof_start(const char* name) {
	int i;
	for (i = 0; i < funcs_cnt; i++) {
		if (!strcmp(name, funcs[i].name)) {
			funcs[i].cnt++;
			funcs[i].last_start = now();
			return;
		}
	}

	strncpy(funcs[i].name, name, 32);
	funcs[i].name[31] = 0;
	funcs[funcs_cnt].cnt = 1;
	funcs[funcs_cnt].last_start = now();
	funcs[funcs_cnt].time_spent = 0;
	funcs_cnt++;
}

void prof_stop(const char *name) {
	int i;
	int64_t tnow = now();
	for (i = 0; i < funcs_cnt; i++) {
		if (!strcmp(name, funcs[i].name)) {
			funcs[i].time_spent += tnow-funcs[i].last_start;
			funcs[i].last_start = 0;
			return;
		}
	}
}
#endif
